using Microsoft.AspNetCore.SignalR.Client;
using MultiAgentsClient.ChatDataStructures;
using MultiAgentsServer.Scripts.Shared.enums;
using MultiAgentsShared;
using static MultiAgentsClient.Manager.UserInfoManager;

namespace MultiAgentsClient.Service.SignalRService;

public class SignalRUserService : SignalRClientServiceBase
{
    public enum ApiRequestType
    {
        RegisterApiRequest,
        ChangePasswordApiRequest,
        LoginApiRequest,
        AutoLoginApiRequest,
        LogoutApiRequest,
        FetchUserdataApiRequest,
    }

    public SignalRUserService() : base("userHub") { }

    protected override void HubMethodRegistration()
    {
        hubConnection.On<StatusCode, int>("LoginApiResponse", LoginApiResponse);
        hubConnection.On<StatusCode>("RegisterApiResponse", RegisterApiResponse);
        hubConnection.On<StatusCode>("ChangePasswordApiResponse", ChangePasswordApiResponse);
        // Dictionary<Id, Name>
        hubConnection.On<string, int, int>("FetchUserdataApiResponse", FetchUserdataApiResponse);

        hubConnection.On<string, string>("StayLoginResponse", StayLoginResponse);
    }

    private void LoginApiResponse(StatusCode status, int userId)
    {
        eventBus.Publish(new LoginResponseCommand(status, userId));
    }

    private void RegisterApiResponse(StatusCode status)
    {
        eventBus.Publish(new RegisterResponseCommand(status));
    }

    private void ChangePasswordApiResponse(StatusCode status)
    {
        eventBus.Publish(new ChangePasswordResponseCommand(status));
    }

    private void StayLoginResponse(string userName, string password)
    {
        eventBus.Publish(new StayLoginResponseCommand(userName, password));
    }

    private string receivedUserDataJson = "";
    private int expectedUserDataJsonSize = 0;

    // Dictionary<Id, Name>
    private void FetchUserdataApiResponse(string userDataJsonChunk, int chunkOffset, int chunkTotalSize)
    {
        if (chunkOffset == 0)
        {
            expectedUserDataJsonSize = chunkTotalSize;
            receivedUserDataJson = "";
        }

        receivedUserDataJson += userDataJsonChunk;

        if (receivedUserDataJson.Length >= expectedUserDataJsonSize)
        {
            UserDataModel userdata = SerializableObjectBase.FromJson<UserDataModel>(receivedUserDataJson);

            if (userdata.Id == -1)
            {
                Debug.LogError("FetchUserdata failed");
                return;
            }

            //TODO: Do not need public whole userdata
            eventBus.Publish(new FetchUserdataResponseCommand(userdata));
        }
    }
}
